import axios from 'axios'
import { AccountSource } from '../types'

interface WxJsCode2SessionRes {
  unionid: string
  openid?: string
  session_key: string
  source: AccountSource
}
interface WxResult {
  data: WxJsCode2SessionRes
}

/**
 * 根据code换取openid,并生成token
 * @param code
 */
export const userAuthenticationService = async function (code: string): Promise<WxJsCode2SessionRes> {
  const appId = process.env.APP_ID
  const appSecret = process.env.APP_SECRET
  if (appId || appSecret) {
    throw new Error('服务端appId或者appSecret未设置')
  }
  const url = `https://api.weixin.qq.com/sns/jscode2session?appid=${appId}&secret=${appSecret}&js_code=${code}&grant_type=authorization_code`

  try {
    const { data } = await axios<any, WxResult>({ url })
    console.log(data, 'data11')
    const { unionid, openid, session_key } = data
    return { unionid, openid, session_key, source: AccountSource.微信小程序 }
  }
  catch (error) {
    return error
  }
}
